/**
 * Created by wdj on 16/4/21.
 * Page
 */
'use strict';
var $ = window.jQuery || Dom7;

var Utils = require('../libs/utils');

var _cacheAppParams;

export default class Controller {

    constructor(app, page) {
        this.__init(app, page);
    }

    __init(app, page){
        this.page = page;
        this.pageContianer = $(page.container);
        this.navbar = $(page.navbarInnerContainer);
        this.view = page.view;
        this.query = page.query;

        this.app = app;
        this.stopPageEvent = this.stopPageEvent || false;
        this.__removeBindEvents();

        this._timeouts = [];
        this._interval = [];

        if(app && app.mainView && app.mainView.params && !_cacheAppParams){
            // 记录app参数
            _cacheAppParams = {};
            _cacheAppParams.swipeBackPage = app.mainView.params.swipeBackPage;
            _cacheAppParams.swipePanel = app.params.swipePanel;
            _cacheAppParams.hardwareBtnBack = app.params.hardwareBtnBack;
            app.mainView.params.hardwareBtnBack = app.params.hardwareBtnBack;
        }
    }

    __removeBindEvents(){
        var bs = this.__bindEvents || [];
        for (var i = 0; i < bs.length; i++) {
            this.find(bs[i].el).off(bs[i].event, bs[i].handler);
            this.find(bs[i].el, this.navbar).off(bs[i].event, bs[i].handler);
        }
        this.__bindEvents = [];
    }

    onPageBeforeInit(app, page) {
        // console.warn(page.name + ' onPageBeforeInit not define');
        this.__init(app, page);
        !this.stopPageEvent && this.onCreate(app, page);

        if(page.name === 'index' && _cacheAppParams){
            this.setSwipePanel(_cacheAppParams.swipePanel);
        }
    }

    onPageInit(app, page) {
        // console.warn(page.name + ' onPageInit not define');
        !this.stopPageEvent && this.onCreated(app, page);

        this.find('.login-required').click(function () {
            if(!app.checkLogin()){
                app.mainView.loadPage('pages/login.jade');
                return false;
            }
        })
    }

    onPageBeforeAnimation(app, page) {
        !this.stopPageEvent && this.onShow(app, page);
        // console.warn(page.name + ' onPageBeforeAnimation not define');
        this.setSwipeBack(this.disableSwipeBack ? false : _cacheAppParams.swipeBackPage);
        this.setSwipePanel(this.disableSwipePanel || page.name !== 'index' ? false : _cacheAppParams.swipePanel);
        this.setHardwareBtnBack(this.disableHardwareBtnBack ? false : _cacheAppParams.hardwareBtnBack);
    }

    onPageAfterAnimation(app, page) {
        !this.stopPageEvent && this.onShown(app, page);
        // console.warn(page.name + ' onPageAfterAnimation not define');
    }

    onPageBeforeRemove(app, page) {
        // console.warn(page.name + ' onPageBeforeRemove not define');
        this.__removeBindEvents();
        this.onDestroy(app, page);

        this._timeouts.forEach(function (t) {
            clearTimeout(t);
        });

        this._interval.forEach(function (t) {
            clearInterval(t);
        });
    }

    onPageBack(app, page) {
        !this.stopPageEvent && this.onBack(app, page);
        // console.warn(page.name + ' onPageBack not define');
    }

    onPageAfterBack(app, page) {
        !this.stopPageEvent && this.onBackd(app, page);
        // console.warn(page.name + ' onPageAfterBack not define');
    }

    /* custom method */

    onCreate(app, page) {
    }

    onCreated(app, page) {
    }

    onShow(app, page) {
    }

    onShown(app, page) {
    }

    onBack(app, page) {
    }

    onBackd(app, page) {
    }

    onDestroy(app, page) {
    }

    importView(viewName, locals) {
        var opt = {
            self: this,
            util: Utils
        };

        var jade = require('./views/' + viewName + '.jade');
        if(locals){
            Utils.extend(locals, opt);
            return jade(locals);
        }
        return jade;
    }

    loadView(viewName, locals, container) {
        //this.app.mainView.loadContent(this.importView(viewName)(locals));
        container = container || '.page-content';
        var $container = this.find(container);
        return $container.html(this.importView(viewName)(locals));
    }

    /**
     * 判断当前页是否在显示
     * @param {string} [pageName] 页面名称
     * @returns {boolean}
     */
    isShow(pageName) {
        var self = this;
        if (self.pageContianer) {
            if (this.pageContianer.closest('.popup').length || this.pageContianer.closest('.login-screen').length) {
                return true;
            }
        }
        return $(document.body).data('page-name') === (pageName || this.page.name);
    }

    /**
     * 显示loding
     */
    showIndicator() {
        if (this.app && this.isShow()) {
            this.app.showIndicator();
        }
    }

    hideIndicator() {
        this.app && this.app.hideIndicator();
    }

    showPreloader(title) {
        if (this.app && this.isShow()) {
            this.app.showPreloader(title);
        }
    }

    hidePreloader() {
        this.app && this.app.hidePreloader();
    }

    showToast(message) {
        if (this.app && this.isShow()) {
            this.app.showToast(message);
        }
    }

    showTips(options, autoCloseTime) {
        if (this.app && this.isShow()) {
            this.app.showTips(options, autoCloseTime);
        }
    }

    showConfirm(text, title, callbackOk, callbackCancel) {
        if (this.app && this.isShow()) {
            this.app.confirm(text, title, callbackOk, callbackCancel);
        }
    }

    showPrompt(text, title, callbackOk, callbackCancel) {
        if (this.app && this.isShow()) {
            this.app.prompt(text, title, callbackOk, callbackCancel);
        }
    }

    showAlert(text, title, callbackOk) {
        if (this.app && this.isShow()) {
            this.app.alert(text, title, callbackOk);
        }
    }

    showModal(options) {
        if (this.app && this.isShow()) {
            this.app.showModal(options);
        }
    }

    showEmptyInfo(text, el, tag){
        var self = this;
        tag = tag || 'div';
        var tpl = '<' + tag + ' class="empty-data-info">' + text + '</' + tag + '>';
        self.find(el || '.page-content').html(tpl);
    }

    /**
     * 监听当前页面事件
     * @param {String} eventName 事件名
     * @param {*} element 页面dom
     * @param {Function} handler 响应函数
     */
    on(eventName, element, handler) {
        this.pageContianer.on(eventName + '.controller', element, handler);
    }

    /**
     * 触发当前页面事件
     * @param {String} eventName 事件名
     * @param {*} eventData 数据
     */
    trigger(eventName, eventData) {
        this.pageContianer.trigger(eventName + '.controller', eventData);
    }

    /**
     * 在当前页面查找 dom 功能类似 jquery $() or find()
     * @param {*} element
     * @param {*} [container]
     * @returns {*}
     */
    find (element, container){
        if(typeof element === "string"){
            if(container){
                if(!container.hasClass){
                    container = $(container);
                }
            }else{
                container = this.pageContianer;
            }
            if(container && typeof container.find === "function"){
                return container.find(element);
            }
        }
        return $(element);
    }

    /**
     * 事件绑定
     * 只支持当前页面(div.page)下的dom绑定
     * @param {*} [container]
     * @param bindings
     */
    bindEvents (bindings, container){
        for(var k in bindings){
            var s = k.split(' '); //用空格分隔获取事件
            var elc, el;
            var e = s.shift();

            s = s.join(' ').split(',');//重组selector
            for (var i = 0; i < s.length; i++) {
                var mts = s[i].match(/\((.*?)\)/);
                if(mts){
                    el = s[i].replace(mts[0], '');
                    elc = mts[1];
                    this.find(el, container).on(e, elc, bindings[k]);
                }else{
                    el = s[i];
                    this.find(el, container).on(e, bindings[k]);
                }
                this.__bindEvents.push({
                    el: el,
                    elc: elc,
                    event: e,
                    handler: bindings[k]
                });
            }
        }
    }

    /**
     * 提供对 navbar 的操作
     * @returns {{find: Function, bindEvents: Function}}
     */
    header(){
        var self = this;
        //if(!self.navbar || !self.navbar.length){
            self.navbar = $('.navbar > .navbar-inner:last-child');
        //}
        return {
            find: function(element){
                return self.find(element, self.navbar);
            },
            bindEvents: function(bindings){
                self.bindEvents(bindings, self.navbar);
            }
        }
    }

    /**
     * setTimeout
     * @param fn
     * @param timeout
     */
    setTimeout(fn, timeout){
        this._timeouts.push(setTimeout(fn, timeout));
    }

    /**
     * setInterval
     * @param fn
     * @param delay
     */
    setInterval(fn, delay){
        this._interval.push(setInterval(fn, delay));
    }

    /**
     * 设置是否允许 swipe back
     * @param bool
     */
    setSwipeBack(bool){
        if(this.view && this.view.params){
            this.view.params.swipeBackPage = bool;
            this.disableSwipeBack = !bool;
        }
    }

    /**
     * 设置是否允许 swipe panel
     * @param bool
     */
    setSwipePanel(bool){
        if(this.app && this.app.params){
            this.app.params.swipePanel = bool;
            this.disableSwipePanel = !bool;
        }
    }

    /**
     * 禁用滑动返回,滑动显示个人信息
     */
    disableSwipe(){
        this.setSwipeBack(false);
        //this.setSwipePanel(false);
    }

    /**
     * 滑动返回,滑动显示个人信息
     */
    enableSwipe(){
        this.setSwipeBack(true);
        //this.setSwipePanel(_cacheAppParams.swipePanel);
    }

    /**
     * 设置是否允许Android Back
     * @param bool
     */
    setHardwareBtnBack(bool){
        if(this.view && this.view.params){
            this.view.params.hardwareBtnBack = bool;
            this.disableHardwareBtnBack = !bool;
        }
    }

    /**
     * 禁用 Android 硬件返回按钮
     */
    disableHardwareBack(){
        this.setHardwareBtnBack(false);
    }

    /**
     *  Android 硬件返回按钮
     */
    enableHardwareBack(){
        this.setHardwareBtnBack(true);
    }
}

module.exports = Controller;
